<?php

namespace app\admin\controller\questionnaire\publish_task;

use app\BaseController;
use app\model\questionnaire\QuestionnaireTaskModel;
use app\model\questionnaire\QuestionnaireTaskPaperModel;
use app\model\questionnaire\QuestionnaireTaskUserModel;
use app\model\questionnaire\QuestionnaireTypeModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 发布任务
     * @return bool|string
     */
    public function index(): bool|string
    {
        $QuestionnaireTaskModel = new QuestionnaireTaskModel();
        $QuestionnaireTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'name|任务名称' => 'require',
                'is_time|限时状态' => 'require',
                'result_read_auth|结果查看权限' => 'require',
                'paper|问卷' => 'require',
                'uids|用户' => 'require',
            ]);
            $param['result_read_auth'] = implode(',',$param['result_read_auth']);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            if (!empty($param['is_time']) && $param['is_time'] == 1) {
                if (empty($param['start_time']) || empty($param['end_time'])) throw new \Exception('请填写开始和结束时间！');
                if ($param['start_time'] >= $param['time'] && $param['end_time'] <= $param['time']) {
                    //在任务时间内将任务设为进行中
                    $param['status'] = 2;
                }
            } else {
                $param['status'] = 2;
            }
            if (!empty($param['uids']) && !empty($param['paper'])){
                $userData = [];
                $paperData = [];
                $param['user_num'] = count($param['uids']);
                $param['paper_num'] = count($param['paper']);
                foreach ($param['paper'] as $paper){
                    $paperData[] = [
                        'paper_id' => $paper['id'],
                        'time' =>$param['time']
                    ];
                    foreach ($param['uids'] as $uid){
                        $userData[] = [
                            'uid' => $uid,
                            'paper_id' => $paper['id'],
                            'time' =>$param['time']
                        ];
                    }
                }
                unset($param['uids']);
                unset($param['paper']);
            }
            $task_id = $QuestionnaireTaskModel->insertGetId($param);
            if (!empty($paperData)) {
                foreach ($paperData as &$v) {
                    $v['task_id'] = $task_id;
                }
                $QuestionnaireTaskPaperModel = new QuestionnaireTaskPaperModel();
                $QuestionnaireTaskPaperModel->insertAll($paperData);
            }
            if (!empty($userData)) {
                foreach ($userData as &$v) {
                    $v['task_id'] = $task_id;
                }
                $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
                $QuestionnaireTaskUserModel->insertAll($userData,200);
            }
            $QuestionnaireTaskModel->commit();
            return success();
        } catch (\Exception $e) {
            $QuestionnaireTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 试卷选择器
     * @return bool|string
     */
    public function PaperSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $PaperWhere = [];
            if (!empty($param['name'])) {
                $PaperWhere[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $PaperWhere[] = ['status', '=', 1];
            $QuestionnaireTypeModel = new QuestionnaireTypeModel();
            $list = $QuestionnaireTypeModel->field('id,name')
                ->where($where)
                ->with([
                    'paper' => function ($query) use ($PaperWhere) {
                        $query->where($PaperWhere)->field('id,type_id,name');
                    }
                ])->order('sort','asc')->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

}